package com.chap1;

/**
 * <p>
 * <code>SynTest</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-03-24 15:11
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class SynInstance2 {
    private static long count = 0;
    private Object obj = new Object();

    public long getCount() {
        return count;
    }

    public void setCount(long count) {
        this.count = count;
    }


    public void incCountBlock(){
        synchronized (this){
            count++;
        }
    }

    public synchronized  static void incCountObj(){
        count++;
    }

    private static class Count extends Thread{
        private SynInstance2 synTest;

        public Count(SynInstance2 synTest) {
            this.synTest = synTest;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10000; i++) {
                synTest.incCountObj();
            }
        }
    }

    private static class Count2 extends Thread{
        private SynInstance2 synTest;

        public Count2(SynInstance2 synTest) {
            this.synTest = synTest;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10000; i++) {
                synTest.incCountBlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SynInstance2 synTest = new SynInstance2();
        Count count1 = new Count(synTest);
        count1.start();
        Count2 count2 = new Count2(synTest);
        count2.start();
        Thread.sleep(50);
        System.out.println(synTest.count);
    }
}
